package com.example.demo.controller;

import com.example.demo.pojo.R;
import com.example.demo.pojo.User.LoginRequest;
import com.example.demo.pojo.User.User;
import com.example.demo.pojo.User.UserInfoDTO;
import com.example.demo.service.UserService;
import com.example.demo.utils.PcUtils.UploadFileUtils;
import com.example.demo.utils.TokenUtil.JwtUtils;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/users")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Resource
    private UserService userService;

    //登录接口
    @PostMapping("/login")
    public R<T> userLogin(@RequestBody LoginRequest loginRequest, HttpServletResponse response,
                          HttpServletRequest request) {
        return userService.userLogin(loginRequest, response, request);
    }


    /**
     * 退出登录接口。
     * 从Cookie中获取用户Token，并处理用户退出登录的逻辑。
     *
     * @param token    用户登录时获取的Token
     * @param response HttpServletResponse对象
     * @return 返回操作结果
     */
    @GetMapping("/outLogin")
    public R<?> outLogin(@CookieValue(name = "token", required = false) String token, HttpServletResponse response) {
        try {
            return userService.outLogin(token, response);
        } catch (Exception e) {
            logger.error("退出失败", e);
            return R.failed("退出失败！");
        }
    }

    //注册接口
    @PostMapping("/register")
    public R<T> register(User user, HttpServletRequest request) {
        return userService.register(user, request);
    }

    /**
     * 找回密码
     *
     * @param email       注册邮箱
     * @param newUserName 新的用户名
     * @param newPassWord 新的密码
     * @param code        验证码
     */
    @PostMapping("/findPassWord")
    public R<T> findPassWord(@RequestParam String email
            , @RequestParam String newUserName
            , @RequestParam String newPassWord
            , @RequestParam String code) {
        return userService.findPassWord(email, newUserName, newPassWord, code);
    }

    /**
     * 修改头像接口
     *
     * @param user 用户
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @PostMapping("/changeAvatar")
    public R<T> changeAvatar(User user,
                             HttpServletRequest request,
                             @CookieValue(name = "token", required = false) String token) throws ServletException, IOException {
        Part newAvatarPart = request.getPart("avatar");
        if (newAvatarPart != null) {
            String oldAvatarPath = user.getHeaderUrl(); // 从数据库中获取的路径
            logger.info(String.valueOf(user));
            File oldAvatarFile = null;
            if (oldAvatarPath != null) {
                oldAvatarFile = UploadFileUtils.getFileFromDbPath(oldAvatarPath); // 转换为文件系统路径
            }
            if (oldAvatarFile != null && oldAvatarFile.exists()) {
                boolean deleted = oldAvatarFile.delete();
                logger.info("旧头像{}删除{}", oldAvatarFile.getAbsolutePath(), deleted ? "成功" : "失败");
            }


            UploadFileUtils.FileResult result = UploadFileUtils.savePart(user.getUserName(), request, newAvatarPart);
            user.setHeaderUrl(result.getUrl());
            logger.info("新头像保存成功 => " + result.getUrl());
        }

        return userService.updateUserAvatar(user, request, token);
    }

    /**
     * 获取当前登录用户信息接口
     */
    @GetMapping("/queryCurrentUserInfo")
    public R<UserInfoDTO> queryCurrentUserInfo(@CookieValue(name = "token", required = false) String token) {
        if (token == null || token.isEmpty() || !JwtUtils.verifyToken(token)) {
            logger.warn("Token为空");
            return R.failed("用户未登录或登录异常");
        }

        try {
            return userService.queryCurrentUserInfo(token);
        } catch (Exception e) {
            logger.error("错误！", e);
            return R.failed("获取用户信息失败");
        }
    }

    /**
     * 修改用户信息接口。
     * 从Cookie中获取用户Token，并更新用户信息。
     *
     * @param user  用户信息对象
     * @param token 用户登录时获取的Token
     * @return 返回操作结果
     */
    @PutMapping("/updateUserInfo")
    public R<?> updateUserInfo(@RequestBody User user, @CookieValue(name = "token", required = false) String token) {
        if (token == null || token.isEmpty() || !JwtUtils.verifyToken(token)) {
            logger.warn("Token为空");
            return R.failed("用户未登录或登录异常");
        }

        try {
            return userService.updateUserInfo(token, user);
        } catch (Exception e) {
            logger.error("错误！", e);
            return R.failed("更新用户信息失败");
        }
    }

    /**
     * 获取vip截止时间
     *
     * @param token token
     * @return 剩余时间
     */
    @GetMapping("/getUserVipExpireDay")
    public R<Long> getUserVipExpireDay(@CookieValue(name = "token", required = false) String token) {
        if (token == null || token.isEmpty() || !JwtUtils.verifyToken(token)) {
            logger.warn("Token为空");
            return R.failed("用户未登录或登录异常");
        }

        try {
            return userService.getUserVipExpireDay(token);
        } catch (Exception e) {
            logger.error("错误！", e);
            return R.failed("获取失败失败");
        }
    }

}
